<template>
  <div>
    <el-tree
      ref="tree"
      :data="permissionData"
      :props="{label:'name'}"
      show-checkbox
      :check-strictly="true"
      default-expand-all
      node-key="id"
    />
    <div class="footer">
      <el-button @click="$emit('close')">取消</el-button>
      <el-button @click="hAssign">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
import { assignPerm, getRoleDetail } from '@/api/settings'
export default {
  props: {
    id: {
      required: true,
      type: String
    }
  },
  data() {
    return {
      permissionData: []
    }
  },
  created() {
    this.loadPermissionList()
    this.loadPermissionRole()
  },
  methods: {
    async loadPermissionList() {
      try {
        const res = await getPermissionList()
        // console.log(res.data)
        this.permissionData = tranListToTreeData(res.data)
      } catch (e) {
        console.log(e)
      }
    },
    async hAssign() {
      // console.log(this.$refs.tree.getCheckedKeys())
      try {
        const ids = this.$refs.tree.getCheckedKeys()
        console.log(this.id)
        const res = await assignPerm({ id: this.id, permIds: ids })
        this.$message.success(res.message)
        this.$emit('close')
      } catch (e) {
        console.log(e)
      }
    },
    async loadPermissionRole() {
      try {
        const res = await getRoleDetail(this.id)
        // console.log(res.data.permIds)
        this.$refs.tree.setCheckedKeys(res.data.permIds)
        this.$nextTick()
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style scoped>
.footer{
  display: flex;
  justify-content: end;
}
</style>

